import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';

import { CommonService } from '../../../../services-common/common.service';
import { LoveSendIdolManageService } from '../love-send-idol-manage.service';


@Component({
  selector: 'app-love-send-idol-edit',
  templateUrl: './love-send-idol-edit.component.html',
  styleUrls: ['./love-send-idol-edit.component.scss']
})
export class LoveSendIdolEditComponent implements OnInit {

  routeParams: any = {};
  formParams: any = {
    state: 5, // 状态 新增 5：草稿
    name: '', // 活动名称
    note: '', // 备注
    total: '', // 活动总额
    proportion: '', // 赠送比例
    highest: '', // 最高赠送

    beginTime: '', // 活动开始时间
    endTime: '', // 活动结束时间
    rule: '', // 规则说明

    colourId: '', // 适用成色 0：全部 1：二手 2：准新
    modelId: '', // 机型list 0：为全部 -1：为全不选
  };

  // 可领取时间
  activityDates: any[] = [];

  // 适用成色
  conditionOptionsC: any = [];
  selectConditionC: any = [];

  // 适用机型
  isModelVisible = false;
  defaultModelKeys: any = [];
  modelAll: boolean = false;

  // loading
  sumitLoading: boolean = false;
  releaseLoading: boolean = false;

  // 规则默认值(格式)
  defaultTuleText: string = '1.活动时间：xxxx.xx.xx 00:00-xxxx.xx.xx 23:59；\n2.活动期间下单并寄出的订单，在成交后可获得爱豆，最高可获得200个（1爱豆=1元，可在爱思商城购物使用）\n3.本次送爱豆活动仅针对二手手机，准新机不参与；\n4.活动赠送爱豆数量有限，先到先得，送完即止，具体以实际到账为准；\n5.若您参与活动，视为同意所有活动规则，活动最终解释权归爱思商城所有,如有疑问请咨询爱思商城客服。';

  constructor(
    private message: NzMessageService,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    private modal: NzModalService,
    private commonService: CommonService,
    private services: LoveSendIdolManageService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  ngOnInit() {
    this.loadConditionData();

    // 新增默认规则说明格式
    if (['0'].includes(this.routeParams.type)) {
      this.formParams.rule = this.defaultTuleText;
    }

    if (['1', '2'].includes(this.routeParams.type)) {
      this.loadDetailData();
    }
  }

  // 指定C端成色
  async loadConditionData() {
    this.conditionOptionsC = await this.commonService.getDictList('machine_condition');
  }

  // load datails
  async loadDetailData() {
    let params = {
      id: this.routeParams.id
    }
    const messId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getLoveActSendIdolDetails(params);
    this.message.remove(messId);
    
    if (code === 0) {
      const { recycleActivityIdol } = data || {};
      this.formParams.state = recycleActivityIdol.state;
      this.formParams.name = recycleActivityIdol.name || ''; // 活动名称
      this.formParams.note = recycleActivityIdol.note || ''; // 备注
      this.formParams.total = recycleActivityIdol.total; // 活动总额
      this.formParams.proportion = recycleActivityIdol.proportion; // 赠送比例
      this.formParams.highest = recycleActivityIdol.highest; // 最高赠送

      this.formParams.beginTime = recycleActivityIdol.beginTime || ''; // 促销开始时间
      this.formParams.endTime = recycleActivityIdol.endTime || ''; // 促销结束时间
      this.activityDates = recycleActivityIdol.beginTime ? [recycleActivityIdol.beginTime, recycleActivityIdol.endTime] : []; // 活动时间dates
      this.formParams.rule = recycleActivityIdol.rule || ''; // 规则说明

      this.formParams.colourId = recycleActivityIdol.colourId; // 适用成色
      if (recycleActivityIdol.colourId == '0') {
        // 全部成色
        this.selectConditionC = this.conditionOptionsC.map((m: any) => +m.id);
      } else {
        this.selectConditionC = recycleActivityIdol.colourId.split(',').map((m: any) => +m);
      }

      this.formParams.modelId = recycleActivityIdol.modelId; // 机型
      this.modelAll = recycleActivityIdol.modelId == '0' ? true : false;
      this.defaultModelKeys = recycleActivityIdol.modelId != '0' ? recycleActivityIdol.modelId.split(',') : [];
    }
  }

  /**
   * ----------------------------------------------------------------
   * 指定机型 Modal Select Tree
   * ----------------------------------------------------------------
   */
  selectMoreModel() {
    this.defaultModelKeys = [];
    this.defaultModelKeys = this.mergeTreeKey();
    this.isModelVisible = true;
  }

  subModelTree(objs: any) {
    this.formParams.modelId = objs.modelList.join(',');
    this.defaultModelKeys = this.mergeTreeKey();
    if (this.defaultModelKeys.length) {
      this.modelAll = false;
    }
  }

  mergeTreeKey() {
    let modelArr = (this.formParams.modelId && this.formParams.modelId != '0') ? this.formParams.modelId.split(',') : [];
    return [...modelArr].map((item: any) => +item);
  }

  modelOwnerAllChange(val: any) {
    this.formParams.modelId = '';
    this.defaultModelKeys = [];
  }

  /**
   * ----------------------------------------------------------------
   * 验证
   * ----------------------------------------------------------------
   */
  isVerifForms() {
    if (this.isEmpty(this.formParams.name)) {
      this.message.warning('请输入活动名称');
      return false;
    } else if (this.isEmpty(this.formParams.total)) {
      this.message.warning('请输入活动总额');
      return false;
    } else if (this.isEmpty(this.formParams.proportion)) {
      this.message.warning('请输入赠送比例');
      return false;
    } else if (this.isEmpty(this.formParams.highest)) {
      this.message.warning('请输入最高赠送');
      return false;
    } else if (!this.activityDates.length) {
      this.message.warning('请选择活动时间');
      return false;
    } else if (this.commonService.isEmpty(this.formParams.rule)) {
      this.message.warning('请输入规则说明');
      return false;
    } else if (this.formParams.rule === this.defaultTuleText) {
      this.message.warning('当前规则说明为默认提示、请编辑规则说明');
      return false;
    } else if (!this.selectConditionC.length) {
      this.message.warning('请选择适用成色');
      return false;
    } else if (!this.modelAll && !this.defaultModelKeys.length) {
      this.message.warning('请选择适用机型');
      return false;
    } else {
      return true;
    }
  }

  /**
   * ----------------------------------------------------------------
   * 保存 | 发布
   * ----------------------------------------------------------------
   */
  async submitForms(status?: number) {
    if (!this.isVerifForms()) {
      return
    }
    let params = {
      ...this.formParams,
      colourId: this.selectConditionC.length === this.conditionOptionsC.length ? '0' : this.selectConditionC.join(','), // 成色
      modelId: this.paramHandle(this.modelAll, this.defaultModelKeys)
    }
    
    status ? (this.releaseLoading = true) : (this.sumitLoading = true);
    // 复制
    if (this.routeParams.type == '2') {
      params.state = 5;
    }
    // 发布
    if (status === 1) {
      params.state = 1;
    }
    // 编辑
    if (this.routeParams.type == '1') {
      params.id = this.routeParams.id;
    }
    // console.log('submit data', params);
    // return
    const {code, data, message}: any = await this.services.editLoveActSendIdolData(params);
    this.releaseLoading = false;
    this.sumitLoading = false;

    if (code === 0) {
      this.message.success('操作成功');
      this.back();
    }
  }

  // params handle 0：为全部 -1：为全不选
  paramHandle(state: boolean, result: any) {
    let tempStr = '';
    if (state) {
      tempStr = '0';
    } else if (!state && !result.length) {
      tempStr = '-1';
    } else {
      if (Object.prototype.toString.call(result) === '[object Array]') {
        tempStr = result.join(',');
      } else {
        tempStr = result;
      }
    }
    return tempStr;
  }

  // 发布
  releaseCoupon() {
    if (!this.isVerifForms()) {
      return
    }

    this.modal.confirm({
      nzTitle: '提示',
      nzContent: '确认发布?',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        this.submitForms(1);
      },
      nzCancelText: '取消'
    });
  }

  /**
   * ----------------------------------------------------------------
   * Other
   * ----------------------------------------------------------------
   */

  onDateChange(result: any[], kes: string[]) {
    this.formParams[kes[0]] = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd HH:mm:ss') : '';
    this.formParams[kes[1]] = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd HH:mm:ss') : '';
  }

  // is Empty
  isEmpty(val: any) {
    if (val === '' || val === undefined || val === null) {
      return true;
    } else {
      return false;
    }
  }

  // back
  back() {
    history.back();
  }

  // 禁止操作
  setDisabled(special?: string) {
    // 编辑: 进行中 仅可编辑规则说明
    if (this.formParams.state === 2 && this.routeParams.type == '1' && !special) {
      return true;
    } else {
      return false;
    }
  }
}
